// pages/image/index.js
const app = getApp()
Page({

    /**
     * 页面的初始数据
     */
    data: {
        url: app.globalData.url,
        images: []
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad(options) {
        if (options) {
            const that = this
            wx.request({
                url: that.data.url + "/file/showPic",
                data: options,
                success(res) {
                    if (res.data.code === 1) {
                        let images = res.data.result;
                        images.sort((e1, e2) => {
                            return e2.uploadDate.localeCompare(e1.uploadDate)
                        })
                        that.setData({ images })
                    }
                }
            })
        }
    },
    // 放大
    toBig(e) {
        this.setData({
            isShow: true,
            current: e.currentTarget.dataset.image
        })
    },
    // 缩小
    close() {
        this.setData({
            isShow: false
        })
    },
    // 删除
    toDelete(e) {
        const that = this
        wx.showModal({
            title: '提示',
            content: '确认删除吗？',
            success(res) {
                if (res.confirm) {
                    wx.request({
                        url: that.data.url + "/file/delete",
                        data: {
                            id: e.currentTarget.dataset.id
                        },
                        success(res) {
                            if (res.data.code === 1) {
                                let images = that.data.images
                                images.splice(e.currentTarget.dataset.index, 1)
                                that.setData({ images })
                                wx.showToast({ title: '删除成功' })
                            }
                        }
                    })
                } else if (res.cancel) {
                    wx.showToast({ title: '取消删除', icon: 'error' })
                }
            }
        })
    },
    // 下载
    download(e) {
        const that = this
        wx.downloadFile({
            url: that.data.url + "/file/download?file=" + e.currentTarget.dataset.url,
            success(res) {
                if (res.statusCode === 200) {
                    wx.saveImageToPhotosAlbum({
                        filePath: res.tempFilePath,
                        success() {
                            wx.showToast({ title: '下载成功' })
                        },
                        fail(error) {
                            wx.showToast({ title: '取消下载', image: '/images/icons/download_error.png'})
                        }
                    })
                }
            }
        })
    }
})